package pig.controller;

import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import pig.model.BoardVO;
import pig.model.CommonDAO;
import pig.model.CommonService;
import pig.model.CustomerVO;
import pig.model.DealVO;
import pig.model.ListVO;
import pig.model.PostBoxVO;
import pig.model.SellerVO;

@Controller
@RequestMapping("/common")
public class CommonController extends MultiActionController {

   @Resource(name="commonServiceImpl")
   private CommonService commonService;

   @RequestMapping("/{viewId}_view.do")
   public String showView(@PathVariable("viewId") String viewId) {
      return viewId + "_view.common";
   }

   /**
    * 상품명으로 리스트 찾기 메서드
    */
   @RequestMapping("find_DealByTitle.do")
   public String findDealByTitle(HttpServletRequest request, HttpServletResponse response, String dealName) {
      List<DealVO> list = commonService.findDealByTitle(dealName);
      if (list == null) {
         request.setAttribute("dealList", "정보와 일치하는 상품이 없습니다");
      } else {
         request.setAttribute("dealList", list);
      }
      return "home";
   }

   /**
    * 카테고리별 상품리스트 보기
    */
   @RequestMapping("/dealListByCategory.do")
   public ModelAndView dealListByCategory(String category) {
	   List<DealVO> list =null;
	   if(category.equals("all")){
		  list = commonService.findAllDealList();		   
	   }else{
		  list = commonService.dealListByCategory(category);		   
	   }
      return new ModelAndView("find_Deal_view.common","list",list);
   } 

   /**
    * 카테고리별로 상품 나열(최신순,마감순,최저가격,최고가격) 메서드
    */
   @RequestMapping("find_DealByCategory.do")
   public ModelAndView findDealByCategory(HttpServletRequest request, HttpServletResponse response, String category, String order) {
	   List<DealVO> list=null;
	   if(order.equals("end")){
		   list = commonService.findDealByEndDate(category);
      }else if(order.equals("new")){
    	  list = commonService.findDealByRegisterDate(category);
      }else if(order.equals("highprice")){
    	  list = commonService.findDealByHighPrice(category);
      }else if(order.equals("lowprice")){
         list = commonService.findDealByLowPrice(category);
      }
      return new ModelAndView("find_Deal_view.common","list",list);
   }
   
   /**
    * 전체 상품 리스트 메서드
    */
   @RequestMapping("/allList.do")
   public String findAllDeal(HttpServletRequest request, HttpServletResponse response) {
      List<DealVO> list = commonService.findAllDeal();
      if (list.isEmpty()) {
         request.setAttribute("dealList", "Empty");
      } else {
         request.setAttribute("dealList", list);
      }
      return "home";
   } 

   /**
    * 아이디 찾기 메서드 조동희 14.11.25
    */
   @RequestMapping("find_Id.do")
   public String findId(HttpServletRequest request, HttpServletResponse response, String name, String birthdate, String email, String member) {
      String id =null;
      
	  if (member.equals("customer"))
         id = commonService.findCustomerId(name, email);
       else if (member.equals("seller"))
    	 id = commonService.findSellerId(name, email);

	  if (id == null)
            request.setAttribute("id", "정보와 일치하는 회원이 없습니다");
      else
    	  request.setAttribute("id", id);
	  
      return "find_Id_Result.common";
   }

   /**
    * 암호 찾기 메서드 조동희 14.11.25
    */
   @RequestMapping("find_Password.do")
   public String findPassword(HttpServletRequest request, String id, String birthdate, String email, String member) {
	  String password = null;
      if (member.equals("customer"))
          password = commonService.findCustomerPassword(id, email);
      else if (member.equals("seller"))
          password = commonService.findSellerPassword(id, email);

      if (password == null)
          request.setAttribute("password", "정보와 일치하는 회원이 없습니다");
      else
    	  request.setAttribute("password", password);
      
      return "find_Password_Result.common";
   }

   /**
    * 구분자를 통하여 구매자,판매자 페이지로 이동
    */
   @RequestMapping("auth_update_MemberInfo.do")
   public ModelAndView updateMemberInfo(HttpServletRequest request, String check) {
	   HttpSession session = request.getSession(false);
      if (check.equals("customer")) {
         CustomerVO customerVO = (CustomerVO) session.getAttribute("login");
         return new ModelAndView("update_CustomerInfo_view.customer", "login", customerVO);
      } else {
         SellerVO sellerVO = (SellerVO) session.getAttribute("login");
         return new ModelAndView("update_SellerInfo_view.seller", "login", sellerVO);
      }
   }

   /**
    * 구매자,판매자 로그인 메서드
    */
   @RequestMapping(value = "login.do", method = RequestMethod.POST)
   public String login(HttpServletRequest request, HttpServletResponse response, String id, String password, String member) {
      String path = "login_fail.common";
      if (member.equals("customer")) {
         CustomerVO customerVO = commonService.customerLogin(id, password);
         if (customerVO != null) {
            HttpSession session = request.getSession();
            session.setAttribute("login", customerVO);
            path = "index";
         }
      } else if(member.equals("seller")) {
         SellerVO sellerVO = commonService.sellerLogin(id, password);
         if (sellerVO != null) {
        	 if(sellerVO.getPermission().equals("0")){
        		 path="login_permission.seller";
        	 }else{
        		 HttpSession session = request.getSession();
        		 session.setAttribute("login", sellerVO);
        		 path = "index";
        	 }
         }
      }
      return path;
   }

   /**
    * 로그아웃 매서드
    */
   @RequestMapping("logout.do")
   public String logout(HttpServletRequest request, HttpServletResponse response) {
      HttpSession session = request.getSession();
      session.invalidate();
      return "index";
   }

   /**
    * QnA 리스트 보기
    * 최근 게시물 5개를 보여주는 메서드 , 이후 페이징시 업데이트 해야 한다. 
    */
   @RequestMapping("/showDealContents.do")
   public ModelAndView showDealContents(String pageNo, String dealNumber) {   
      DealVO dealVo = commonService.findDealByNumber(dealNumber);   // 딜번호로 정보 찾아오기
      ListVO lvo = commonService.getQNAList(pageNo,dealNumber);
      HashMap map = new HashMap();
      map.put("dealVo", dealVo);
      map.put("lvo", lvo);
      return new ModelAndView("show_DealContents.common","map",map);
   }
    
   /**
    * qna 글쓰기 페이지로 이동
    */
   @RequestMapping("qnaWriteView.do")
   public ModelAndView qnaWrite(String dealNumber) {
      DealVO dealVo = commonService.findDealByNumber(dealNumber);
      HashMap map = new HashMap();
      map.put("dealVo", dealVo);
      return new ModelAndView("qna_Write.common","map",map);
   }

   /**
    * qna 글 등록
    */
   @RequestMapping(value="qnaWrite.do",method=RequestMethod.POST)   
   public ModelAndView write(BoardVO bvo, String dealNumber, HttpServletRequest request) {   
      HttpSession session = request.getSession(false);
      CustomerVO customerVO = (CustomerVO) session.getAttribute("login");
      bvo.setWriter(customerVO.getCustomerId());
      commonService.write(bvo);
      return new ModelAndView("redirect:showContentNoHit.do?dealNumber="+dealNumber+"&no="+bvo.getNo());
   }   
   
   /**
    * 등록, 수정시 사용하는 개별 게시물 조회 메서드 
    */
      @RequestMapping("showContentNoHit.do")
      public ModelAndView showContentNoHit(int no, String dealNumber) {   
         DealVO dealVo = commonService.findDealByNumber(dealNumber);
         BoardVO bvo = commonService.showContentNoHit(no);
         HashMap map = new HashMap();
         map.put("dealVo", dealVo);
         map.put("bvo", bvo);
         return new ModelAndView("qna_ShowContent.common","map",map);
      }
   
      /**
       * 게시물 상세보기
       */
      @RequestMapping("showContent.do")
      public ModelAndView showContent(int no, String dealNumber,
            @CookieValue(value="springboard2",required=false) String cookieValue,HttpServletResponse response) {      
         BoardVO bvo=null;
         if(cookieValue==null){
            response.addCookie(new Cookie("springboard2","|"+no+"|"));
            bvo=commonService.showContent(no);
         }else if(cookieValue.indexOf("|"+no+"|")==-1){
            cookieValue+="|"+no+"|";
            //글번호를 쿠키에 추가 
            response.addCookie(new Cookie("springboard2",cookieValue));
            bvo=commonService.showContent(no);
         }else{
            bvo=commonService.showContentNoHit(no);
         }      
         DealVO dealVo = commonService.findDealByNumber(dealNumber);
         HashMap map = new HashMap();
         map.put("dealVo", dealVo);
         map.put("bvo", bvo);
         
         return new ModelAndView("qna_ShowContent.common","map",map);
      }
      
      /**
       * 답글다는 화면으로 이동
       */
      @RequestMapping("replyView.do")
      public ModelAndView replyView(int no, String dealNumber) {      
         DealVO dealVo = commonService.findDealByNumber(dealNumber);
         BoardVO bvo = commonService.showContentNoHit(no);
         HashMap map = new HashMap();
         map.put("dealVo", dealVo);
         map.put("bvo", bvo);
         return new ModelAndView("qna_Reply.common","map",map);
      }
      
      /**
       * 답글을 저장한다.
       */
      @Transactional
      @RequestMapping("reply.do")
      public ModelAndView reply(BoardVO bvo, String dealNumber, HttpServletRequest request) throws Exception{      
         HttpSession session = request.getSession(false);
         SellerVO sellerVO = (SellerVO) session.getAttribute("login");
         bvo.setWriter("판매자");
         DealVO dealVo = commonService.findDealByNumber(dealNumber);
         commonService.replyWrite(bvo);
         BoardVO bvo2 =commonService.showContentNoHit(bvo.getNo());
         HashMap map = new HashMap();
         map.put("dealVo", dealVo);
         map.put("bvo", bvo2);
         return new ModelAndView("qna_ShowContent.common","map",map);
      }
      
      /**
       * 글을 삭제한다.
       */
      @RequestMapping("deleteBoard.do")
      public ModelAndView deleteBoard(String no,String dealNumber) {      
         commonService.deleteBoard(no);
         ListVO lvo = commonService.getQNAList("1",dealNumber);
         DealVO dealVo = commonService.findDealByNumber(dealNumber);
         HashMap map = new HashMap();
         map.put("dealVo", dealVo);
         map.put("lvo", lvo);
         return new ModelAndView("qna_ShowContent.common","map",map);
      }
      
      /**
       * 글 수정하러 가기
       */
      @RequestMapping("updateView.do")
      public ModelAndView updateView(int no,String dealNumber) {
         BoardVO bvo =commonService.showContentNoHit(no);
         DealVO dealVo = commonService.findDealByNumber(dealNumber);
         HashMap map = new HashMap();
         map.put("dealVo", dealVo);
         map.put("bvo", bvo);
         return new ModelAndView("qna_Update.common","map",map);
      }
      
      /**
       * 글 수정하기
       */
      @RequestMapping(value="updateBoard.do",method=RequestMethod.POST)
      public ModelAndView updateBoard(BoardVO bvo, String dealNumber) {
         commonService.updateBoard(bvo);
         DealVO dealVo = commonService.findDealByNumber(dealNumber);
         BoardVO bvo2 =commonService.showContentNoHit(bvo.getNo());
         HashMap map = new HashMap();
         map.put("dealVo", dealVo);
         map.put("bvo", bvo2);
         return new ModelAndView("qna_ShowContent.common","map",map);
      }
      
  	/**
  	 * 관리자 문의 쪽지 보여주기
  	 */
  	@RequestMapping("sendMessage.do")
  	public ModelAndView sendMessage(){
  		return new ModelAndView("post_Write.tab");
  	}
  	/**
  	 * 관리자에게 쪽지 보내기
  	 */
  	@RequestMapping("postMessage.do")
  	public void postMessage(PostBoxVO postBoxVO,String auth,String id){
  		postBoxVO.setSendAuthNumber(auth);
  		postBoxVO.setReceiveAuthNumber("100");
  		postBoxVO.setReceiverId("admin");
  		commonService.postMessage(postBoxVO);
  	}
  	
  	/**
  	 * 쪽지함 보기 (수신메세지)
  	 */
    @RequestMapping("auth_postList.do")    
   	public ModelAndView postList(HttpServletRequest request,String auth,String id,String post,String pageNo) {
    	ListVO lvo=commonService.postShowSendList(pageNo,id,auth,post);
    	request.setAttribute("post", post);
    	return new ModelAndView("post_List.common","lvo",lvo);
   	}
    
    /**
     * 쪽지 상세보기
     * 수신 변경
     */
    @RequestMapping("postShowContent.do")
    public ModelAndView postShowContent(HttpServletRequest request,String postNum,String check){
       int postNumber=Integer.parseInt(postNum);
       PostBoxVO postBoxVO=commonService.postShowContent(postNumber);
       if(check.equals("receive")){
    	   commonService.postShowContentCheck(postNumber);//수신 여부 확인
       }
       request.setAttribute("check", check);
       return new ModelAndView("post_ShowContent.common","postBoxVO",postBoxVO);
    }
    
   /**
    * 쪽지 답장 페이지 이동
    * 최윤우 14.12.04
    */
    @RequestMapping("postAnswerView.do")
	public ModelAndView postAnswerView(String postNum){
		int postNumber=Integer.parseInt(postNum);
		commonService.postShowContentCheck(postNumber);
		PostBoxVO postBoxVO=commonService.postShowContent(postNumber);
	return new ModelAndView("post_Answer.tab","postBoxVO",postBoxVO);
	}
    
    /**
     * 쪽지 답장
     */
    @RequestMapping("postAnswer.do")
    public void postAnswer(PostBoxVO postBoxVO){
    	commonService.postMessage(postBoxVO);
    }
    
    /**
     * 쪽지 삭제
     */
    @RequestMapping("deletePost.do")
    public String deletePost(String deleteCheck,String post,String postNum){
    	int postNumber=Integer.parseInt(postNum);
    	int deleteOk=Integer.parseInt(deleteCheck);
    	
    	commonService.postReceiveDeleteCheck(deleteOk,postNumber);
    	PostBoxVO postBoxVO=commonService.postShowContent(postNumber);
    	
    	String sendDel=postBoxVO.getSenderDeleteCheck();
    	String receiveDel=postBoxVO.getReceiverDeleteCheck();
    	if(sendDel.equals(receiveDel)){
    		commonService.deletePost(postNumber);
    	}
    	
    	return "redirect:common/allList.do";
    }

}